/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * MantPapelTrabajo.java
 *
 * Created on 12/09/2011, 03:51:47 PM
 */

package GUI.AdministracionPlantillas;

import BE.PlantillaMarcoReferencia;
import BE.PlantillaPapelTrabajo;
import BE.Seccion;
import BL.PlantillaMarcoReferenciaBl;
import BL.PlantillaPapelTrabajoBl;
import BL.SeccionBl;
import GUI.AdministracionUsuarios.UtilUsuarios;
import GUI.Principal;
import java.awt.Dialog.ModalExclusionType;
import java.util.List;
import java.util.Set;
import java.util.Vector;
import javax.swing.ComboBoxModel;
import javax.swing.JComboBox;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author CarLita
 */
public class MantPapelTrabajo extends javax.swing.JFrame {
    PlantillaMarcoReferencia marcoReferencia;
    PlantillaMarcoReferenciaBl marcoReferenciaBl;
    PlantillaPapelTrabajo papelTrabajo;
    PlantillaPapelTrabajoBl papelTrabajoBl;
    SeccionBl seccionBl;
    int modoVentana;
    Principal ventanaPrincipal;
    
    /** Creates new form MantPapelTrabajo */
    public MantPapelTrabajo(Principal ventanaPrincipal) {
        initComponents();
        this.ventanaPrincipal = ventanaPrincipal;
        seccionBl = new SeccionBl();
        setearModo(Principal.MODO_CREACION);
        papelTrabajoBl = new PlantillaPapelTrabajoBl();        
        llenarComboTipos();
        bloquearPorPermisos();
    }

    MantPapelTrabajo(PlantillaPapelTrabajo papelTrabajo, int modo, Principal ventanaPrincipal) {
        initComponents();
        this.papelTrabajo = papelTrabajo;        
        this.ventanaPrincipal = ventanaPrincipal;
        marcoReferenciaBl = new PlantillaMarcoReferenciaBl();
        marcoReferencia = marcoReferenciaBl.buscarPorId(papelTrabajo.getPlantillaMarcoReferencia().getIdPlantilla());
        System.out.println("Marco de referencia nivel 1: " + marcoReferencia.getNivel1Composicion());
        seccionBl = new SeccionBl();        
        papelTrabajoBl = new PlantillaPapelTrabajoBl();
        setearModo(modo);
        llenarComboTipos();
        buscarSecciones();

    }

    MantPapelTrabajo(PlantillaMarcoReferencia plantillaNueva, Principal ventanaPrincipal) {
        marcoReferencia = plantillaNueva;
        this.ventanaPrincipal = ventanaPrincipal;
        initComponents();
        seccionBl = new SeccionBl();
       setearModo(Principal.MODO_CREACION);
       papelTrabajoBl = new PlantillaPapelTrabajoBl();       
       llenarComboTipos();
    }


    public void setearModo(int modo){
        modoVentana = modo;
        switch(modo){
            case Principal.MODO_CREACION:
                btnEditar.setVisible(false);
                btnLimpiar.setVisible(true);
                btnGuardar.setVisible(true);
                llenarInformacionNiveles();
                bloquearPestaña(true);
                break;
            case Principal.MODO_EDICION:
                btnEditar.setVisible(false);
                btnLimpiar.setVisible(false);
                btnGuardar.setVisible(true);
                llenarInformacionPT();
                bloquearCampos(false);
                bloquearPestaña(false);
                break;
            case Principal.MODO_LECTURA:
                btnLimpiar.setVisible(false);
                btnGuardar.setVisible(false);
                btnEditar.setVisible(true);
                llenarInformacionPT();
                bloquearCampos(true);
                bloquearPestaña(false);
                break;
            case Principal.MODO_LLENADO:
                btnLimpiar.setVisible(false);
                btnEditar.setVisible(true);
                btnGuardar.setVisible(true);
                llenarInformacionPT();
                bloquearPestaña(false);
                break;
        }

    }

    public void llenarInformacionPT(){
        txtNombre.setText(papelTrabajo.getNombre());
        txtDescripcion.setText(papelTrabajo.getDescripcion());        
        Object[] secciones = seccionBl.buscarPorIdPlantilla(papelTrabajo.getIdPlantillaPt());
        llenarInformacionNiveles();
        llenarTabla(secciones);
    }

    private void llenarInformacionNiveles(){
        lblNivel1.setText(marcoReferencia.getNivel1Composicion()+ ":");
            System.out.println("llenar informacion niveles");
            System.out.println("nvel 2:" + marcoReferencia.getNivel2Composicion());
            System.out.println("nvel 3:" + marcoReferencia.getNivel3Composicion());

        if (papelTrabajo != null){
            txtNivel1.setText(papelTrabajo.getNivel1());
        }
        if (marcoReferencia.getNivel2Composicion().trim().isEmpty()){
            lblNivel2.setText("{Nivel 2}:");
            txtNivel2.setEnabled(false);
        }
         else{
            lblNivel2.setText(marcoReferencia.getNivel2Composicion()+ ":");
            if (papelTrabajo!= null)
            txtNivel2.setText(papelTrabajo.getNivel2());
         }

        if (marcoReferencia.getNivel3Composicion().trim().isEmpty()){
            lblNivel3.setText("{Nivel 3}:");
            txtNivel3.setEnabled(false);
        }
         else {
            lblNivel3.setText(marcoReferencia.getNivel3Composicion()+ ":");
            if (papelTrabajo!= null) txtNivel3.setText(papelTrabajo.getNivel3());
            /*else {
                lblNivel3.setText("{Nivel 3}:");
                txtNivel3.setEnabled(false);
            } */          
            
         }
    }

    private void bloquearCampos(boolean bloquear){
        boolean desbloqueado = !bloquear;
        btnAgregarSeccion.setEnabled(desbloqueado);
        btnEditarSeccion.setEnabled(desbloqueado);
        btnEliminarSeccion.setEnabled(desbloqueado);

        txtNombre.setEditable(desbloqueado);
        txtNivel1.setEditable(desbloqueado);
        txtNivel2.setEditable(desbloqueado);
        txtNivel3.setEditable(desbloqueado);
        cmbTipoPT.setEnabled(desbloqueado);
        txtDescripcion.setEditable(desbloqueado);

    }

    private void bloquearPestaña(boolean b) {
        tabPapelTrabajo.setEnabledAt(tabPapelTrabajo.getTabCount()-1, !b);
    }
    private void limpiarTablaSecciones() {
        tblSecciones.setModel(new DefaultTableModel(
                new Object [][] {},
            new String [] {
                "Id", "Indice", "Nombre"
            }));
        ocultarIdTabla();

    }

    private void ocultarIdTabla() {
        tblSecciones.getColumn("Id").setWidth(0);
        tblSecciones.getColumn("Id").setMinWidth(0);
        tblSecciones.getColumn("Id").setMaxWidth(0);
    }


    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        tabPapelTrabajo = new javax.swing.JTabbedPane();
        jPanel1 = new javax.swing.JPanel();
        txtNombre = new javax.swing.JTextField();
        jLabel12 = new javax.swing.JLabel();
        lblNivel1 = new javax.swing.JLabel();
        lblNivel2 = new javax.swing.JLabel();
        lblNivel3 = new javax.swing.JLabel();
        jLabel13 = new javax.swing.JLabel();
        cmbTipoPT = new javax.swing.JComboBox();
        jScrollPane1 = new javax.swing.JScrollPane();
        txtDescripcion = new javax.swing.JTextArea();
        jLabel14 = new javax.swing.JLabel();
        btnGuardar = new javax.swing.JButton();
        btnLimpiar = new javax.swing.JButton();
        btnCancelar = new javax.swing.JButton();
        btnEditar = new javax.swing.JButton();
        txtNivel1 = new javax.swing.JTextField();
        txtNivel2 = new javax.swing.JTextField();
        txtNivel3 = new javax.swing.JTextField();
        jPanel2 = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        tblSecciones = new javax.swing.JTable();
        btnAgregarSeccion = new javax.swing.JButton();
        btnEditarSeccion = new javax.swing.JButton();
        btnEliminarSeccion = new javax.swing.JButton();
        btnRefrescar = new javax.swing.JButton();
        jLabel4 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jPanel1.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        jLabel12.setText("Nombre:");

        lblNivel1.setText("{Nivel1}:");

        lblNivel2.setText("{Nivel2}:");

        lblNivel3.setText("{Nivel3}:");

        jLabel13.setText("Tipo:");

        txtDescripcion.setColumns(20);
        txtDescripcion.setFont(new java.awt.Font("Tahoma", 0, 11));
        txtDescripcion.setRows(5);
        jScrollPane1.setViewportView(txtDescripcion);

        jLabel14.setText("Descripción:");

        btnGuardar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/GUI/AdministracionPlantillas/guardar.png"))); // NOI18N
        btnGuardar.setText("Guardar");
        btnGuardar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnGuardarActionPerformed(evt);
            }
        });

        btnLimpiar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/GUI/AdministracionPlantillas/limpiar.png"))); // NOI18N
        btnLimpiar.setText("Limpiar");
        btnLimpiar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnLimpiarActionPerformed(evt);
            }
        });

        btnCancelar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/GUI/AdministracionPlantillas/cancelar.png"))); // NOI18N
        btnCancelar.setText("Cancelar");
        btnCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelarActionPerformed(evt);
            }
        });

        btnEditar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/GUI/AdministracionPlantillas/edit.gif"))); // NOI18N
        btnEditar.setText("Editar");
        btnEditar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnEditarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(36, 36, 36)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(jLabel14, javax.swing.GroupLayout.PREFERRED_SIZE, 89, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED))
                            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(jPanel1Layout.createSequentialGroup()
                                        .addComponent(jLabel12, javax.swing.GroupLayout.PREFERRED_SIZE, 89, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED))
                                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                                        .addComponent(lblNivel1, javax.swing.GroupLayout.DEFAULT_SIZE, 114, Short.MAX_VALUE)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 10, javax.swing.GroupLayout.PREFERRED_SIZE))
                                    .addGroup(jPanel1Layout.createSequentialGroup()
                                        .addComponent(lblNivel2, javax.swing.GroupLayout.DEFAULT_SIZE, 120, Short.MAX_VALUE)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED))
                                    .addGroup(jPanel1Layout.createSequentialGroup()
                                        .addComponent(lblNivel3, javax.swing.GroupLayout.DEFAULT_SIZE, 120, Short.MAX_VALUE)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)))
                                .addGroup(jPanel1Layout.createSequentialGroup()
                                    .addComponent(jLabel13, javax.swing.GroupLayout.PREFERRED_SIZE, 89, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addGap(35, 35, 35))))
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(jPanel1Layout.createSequentialGroup()
                                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 286, Short.MAX_VALUE)
                                            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                                .addComponent(cmbTipoPT, javax.swing.GroupLayout.Alignment.LEADING, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                                .addComponent(txtNombre, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 286, javax.swing.GroupLayout.PREFERRED_SIZE)))
                                        .addGap(29, 29, 29))
                                    .addGroup(jPanel1Layout.createSequentialGroup()
                                        .addComponent(txtNivel1, javax.swing.GroupLayout.PREFERRED_SIZE, 286, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)))
                                .addGap(91, 91, 91))
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(txtNivel3, javax.swing.GroupLayout.PREFERRED_SIZE, 286, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(txtNivel2, javax.swing.GroupLayout.PREFERRED_SIZE, 286, javax.swing.GroupLayout.PREFERRED_SIZE)))))
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup()
                        .addGap(20, 20, 20)
                        .addComponent(btnEditar, javax.swing.GroupLayout.PREFERRED_SIZE, 123, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(btnGuardar, javax.swing.GroupLayout.PREFERRED_SIZE, 123, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(btnLimpiar, javax.swing.GroupLayout.PREFERRED_SIZE, 123, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(btnCancelar, javax.swing.GroupLayout.PREFERRED_SIZE, 123, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(42, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtNombre, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel12))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblNivel1, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(txtNivel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblNivel2)
                    .addComponent(txtNivel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblNivel3)
                    .addComponent(txtNivel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel13)
                    .addComponent(cmbTipoPT, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel14)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 97, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 49, Short.MAX_VALUE)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnLimpiar)
                    .addComponent(btnGuardar)
                    .addComponent(btnCancelar)
                    .addComponent(btnEditar))
                .addContainerGap())
        );

        tabPapelTrabajo.addTab("Datos Generales", jPanel1);

        tblSecciones.setModel(new DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null}},
            new String [] {
                "Id", "Indice", "Nombre"
            }));
            ocultarIdTabla();
            tblSecciones.addMouseListener(new java.awt.event.MouseAdapter() {
                public void mousePressed(java.awt.event.MouseEvent evt) {
                    tblSeccionesMousePressed(evt);
                }
            });
            jScrollPane2.setViewportView(tblSecciones);

            btnAgregarSeccion.setIcon(new javax.swing.ImageIcon(getClass().getResource("/GUI/AdministracionPlantillas/new doc.png"))); // NOI18N
            btnAgregarSeccion.setText("Agregar");
            btnAgregarSeccion.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
            btnAgregarSeccion.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
            btnAgregarSeccion.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    btnAgregarSeccionActionPerformed(evt);
                }
            });

            btnEditarSeccion.setIcon(new javax.swing.ImageIcon(getClass().getResource("/GUI/AdministracionPlantillas/edit.gif"))); // NOI18N
            btnEditarSeccion.setText("Editar");
            btnEditarSeccion.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    btnEditarSeccionActionPerformed(evt);
                }
            });

            btnEliminarSeccion.setIcon(new javax.swing.ImageIcon(getClass().getResource("/GUI/AdministracionPlantillas/minus white.png"))); // NOI18N
            btnEliminarSeccion.setText("Eliminar");
            btnEliminarSeccion.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    btnEliminarSeccionActionPerformed(evt);
                }
            });

            btnRefrescar.setText("Refrescar");
            btnRefrescar.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    btnRefrescarActionPerformed(evt);
                }
            });

            javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
            jPanel2.setLayout(jPanel2Layout);
            jPanel2Layout.setHorizontalGroup(
                jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(jPanel2Layout.createSequentialGroup()
                    .addGap(30, 30, 30)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGap(18, 18, 18)
                    .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                        .addComponent(btnRefrescar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(btnEliminarSeccion, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(btnAgregarSeccion, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(btnEditarSeccion, javax.swing.GroupLayout.DEFAULT_SIZE, 93, Short.MAX_VALUE))
                    .addContainerGap(19, Short.MAX_VALUE))
            );
            jPanel2Layout.setVerticalGroup(
                jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(jPanel2Layout.createSequentialGroup()
                    .addGap(24, 24, 24)
                    .addComponent(btnAgregarSeccion, javax.swing.GroupLayout.PREFERRED_SIZE, 73, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(btnEditarSeccion)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(btnEliminarSeccion)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                    .addComponent(btnRefrescar)
                    .addGap(158, 158, 158))
                .addGroup(jPanel2Layout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 337, Short.MAX_VALUE)
                    .addContainerGap())
            );

            tabPapelTrabajo.addTab("Secciones", jPanel2);

            jLabel4.setFont(new java.awt.Font("Verdana", 0, 24));
            jLabel4.setIcon(new javax.swing.ImageIcon(getClass().getResource("/GUI/imagenes/lista-de-regalos.png"))); // NOI18N
            jLabel4.setText("Papel de Trabajo");

            javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(jLabel4))
                .addComponent(tabPapelTrabajo, javax.swing.GroupLayout.PREFERRED_SIZE, 617, javax.swing.GroupLayout.PREFERRED_SIZE)
            );
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addComponent(jLabel4)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(tabPapelTrabajo, javax.swing.GroupLayout.PREFERRED_SIZE, 387, javax.swing.GroupLayout.PREFERRED_SIZE))
            );

            pack();
        }// </editor-fold>//GEN-END:initComponents

    private void btnEliminarSeccionActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEliminarSeccionActionPerformed
        if (tblSecciones.getSelectedRow()==-1){
            JOptionPane.showMessageDialog(this, "Seleccione una sección para eliminar", "Error", JOptionPane.ERROR_MESSAGE);
            return;
        }
        Seccion seccionSeleccionada = getSeccionSeleccionada();
        int opcion = JOptionPane.showConfirmDialog(this, "Está seguro que desea borrar esta sección?", "Confirmación", JOptionPane.ERROR_MESSAGE);
        if (opcion == JOptionPane.YES_OPTION){
            boolean borrado = papelTrabajoBl.borrar(seccionSeleccionada);
            if (borrado){
                JOptionPane.showMessageDialog(this, "La seccion seleccionada ha sido eliminada", "Confirmacion", JOptionPane.INFORMATION_MESSAGE);
                buscarSecciones();
            }
            else JOptionPane.showMessageDialog(this, "Ha ocurrido un error en la eliminación.\nPor favor, intente nuevamente.", "Error", JOptionPane.ERROR_MESSAGE);
        }

    }//GEN-LAST:event_btnEliminarSeccionActionPerformed

    private void btnAgregarSeccionActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAgregarSeccionActionPerformed
        crearSeccion();
        buscarSecciones();
    }//GEN-LAST:event_btnAgregarSeccionActionPerformed

    private void btnLimpiarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnLimpiarActionPerformed
        limpiar();
    }//GEN-LAST:event_btnLimpiarActionPerformed

    private void limpiar(){
        txtNombre.setText("");
        txtNivel1.setText("");
        txtNivel2.setText("");
        txtNivel3.setText("");
        txtDescripcion.setText("");
        cmbTipoPT.setSelectedIndex(0);
        limpiarTablaSecciones();
    }

    private void btnEditarSeccionActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEditarSeccionActionPerformed
        if (tblSecciones.getSelectedRow()==-1){
            JOptionPane.showMessageDialog(this, "Seleccione una sección para editar", "Error", JOptionPane.ERROR_MESSAGE);
            return;
        }
        Seccion seccionSeleccionada = getSeccionSeleccionada();
        new MantSeccion(papelTrabajo,seccionSeleccionada,Principal.MODO_EDICION, ventanaPrincipal).setVisible(true);        
        buscarSecciones();
    }//GEN-LAST:event_btnEditarSeccionActionPerformed

    private void btnGuardarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnGuardarActionPerformed
        guardar();      
    }//GEN-LAST:event_btnGuardarActionPerformed

    private void btnEditarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEditarActionPerformed
        setearModo(Principal.MODO_EDICION);
    }//GEN-LAST:event_btnEditarActionPerformed

    private void btnCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelarActionPerformed
        this.dispose();
    }//GEN-LAST:event_btnCancelarActionPerformed

    private void tblSeccionesMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tblSeccionesMousePressed
        if (evt.getClickCount()>1){
            lecturaSeccion();
        }
    }//GEN-LAST:event_tblSeccionesMousePressed

private void btnRefrescarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnRefrescarActionPerformed
    buscarSecciones();
}//GEN-LAST:event_btnRefrescarActionPerformed

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                //new MantPapelTrabajo().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAgregarSeccion;
    private javax.swing.JButton btnCancelar;
    private javax.swing.JButton btnEditar;
    private javax.swing.JButton btnEditarSeccion;
    private javax.swing.JButton btnEliminarSeccion;
    private javax.swing.JButton btnGuardar;
    private javax.swing.JButton btnLimpiar;
    private javax.swing.JButton btnRefrescar;
    private javax.swing.JComboBox cmbTipoPT;
    private javax.swing.JLabel jLabel12;
    private javax.swing.JLabel jLabel13;
    private javax.swing.JLabel jLabel14;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JLabel lblNivel1;
    private javax.swing.JLabel lblNivel2;
    private javax.swing.JLabel lblNivel3;
    private javax.swing.JTabbedPane tabPapelTrabajo;
    private javax.swing.JTable tblSecciones;
    private javax.swing.JTextArea txtDescripcion;
    private javax.swing.JTextField txtNivel1;
    private javax.swing.JTextField txtNivel2;
    private javax.swing.JTextField txtNivel3;
    private javax.swing.JTextField txtNombre;
    // End of variables declaration//GEN-END:variables

    private Seccion getSeccionSeleccionada() {
        int idSeccion = Integer.parseInt(tblSecciones.getValueAt(tblSecciones.getSelectedRow(), 0).toString());
        Seccion s = seccionBl.buscarPorId(idSeccion);
        //System.out.println("Id PT de seccion seleccionada: "+ s.);
        return s;
    }

    private String validarCampos() {
        String msjError = "";        
        if (txtNombre.getText().trim().isEmpty())
            msjError= "Usted no ha indicado el nombre del nuevo papel de trabajo.";
        return msjError;

    }

    private boolean crearPapelTrabajo() {
        papelTrabajo = new PlantillaPapelTrabajo();
        llenarDatosPapelTrabajo();
        return papelTrabajoBl.guardar(papelTrabajo);
    }

    private boolean editarPapelTrabajo(){
        llenarDatosPapelTrabajo();
        return papelTrabajoBl.guardar(papelTrabajo);
    }

    private void llenarDatosPapelTrabajo(){
        papelTrabajo.setNombre(txtNombre.getText().trim());
        String n1 = txtNivel1.getText().trim();
        papelTrabajo.setNivel1(n1.isEmpty()?"":n1);
        String n2 = txtNivel2.getText().trim();
        papelTrabajo.setNivel2(n2.isEmpty()?"":n2);
        String n3 = txtNivel3.getText().trim();
        papelTrabajo.setNivel3(n3.isEmpty()?"":n3);
        papelTrabajo.setDescripcion(txtDescripcion.getText().trim());
        papelTrabajo.setTipo(cmbTipoPT.getSelectedIndex());
        papelTrabajo.setPlantillaMarcoReferencia(marcoReferencia);
    }

    private void llenarComboTipos() {
        for (String s: PlantillaPapelTrabajo.TIPOS_PT){
            cmbTipoPT.addItem(s);
        }
    }

    private void crearSeccion() {
        MantSeccion s = new MantSeccion(papelTrabajo, ventanaPrincipal);        
        s.setModalExclusionType(ModalExclusionType.APPLICATION_EXCLUDE);
        s.setVisible(true);
        buscarSecciones();
    }

    private void buscarSecciones() {
        Object[] seccionesActivas = seccionBl.buscarPorIdPlantilla(papelTrabajo.getIdPlantillaPt());
        llenarTabla(seccionesActivas);
    }

    private void llenarTabla(Object[] seccionesActivas) {
        Vector<String> tableHeaders = new Vector<String>();
        Vector tableData = new Vector();
        tableHeaders.add("Id");
        tableHeaders.add("Indice");
        tableHeaders.add("Nombre");

        for(Object o : seccionesActivas) {
            Seccion seccion = (Seccion)o;
            Vector<Object> fila = new Vector<Object>();
            fila.add(seccion.getIdSeccion());
            String s = calcularIndice(seccion);
            fila.add(s);
            fila.add(seccion.getTitulo());
            tableData.add(fila);
        }

        tblSecciones.setModel(new DefaultTableModel(tableData, tableHeaders));
        ocultarIdTabla();
    }
    
    private String calcularIndice(Seccion seccion){
        String s= ""+seccion.getCorrelativo();
        if (seccion.getCorrelativoSuperior2()!=0){
            s = seccion.getCorrelativoSuperior2()+"."+s;            
        }        
        if (seccion.getCorrelativoSuperior1()!=0)
            s = seccion.getCorrelativoSuperior1()+"."+s;
        return s;
    }

    private void lecturaSeccion() {
        Seccion s = getSeccionSeleccionada();
        new MantSeccion(papelTrabajo, s, Principal.MODO_LECTURA, ventanaPrincipal).setVisible(true);
        buscarSecciones();
    }

    private void guardar() {
         String msjError = validarCampos();
        if (modoVentana == Principal.MODO_CREACION){
            if (msjError.isEmpty()){
            boolean creado = crearPapelTrabajo();
                if (creado) {                    
                    setearModo(Principal.MODO_EDICION);
                    JOptionPane.showMessageDialog(this, "El nuevo papel de trabajo ha sido creado", "Confirmación", JOptionPane.INFORMATION_MESSAGE);
                }
                else {
                    JOptionPane.showMessageDialog(this, "Ha ocurrido un error en la creación", "Error", JOptionPane.ERROR_MESSAGE);
                }
            }
             else{
                JOptionPane.showMessageDialog(this, msjError, "Error", JOptionPane.ERROR_MESSAGE);
             }
        }
         else {
            boolean editado = editarPapelTrabajo();
            if (editado) JOptionPane.showMessageDialog(this, "El papel de trabajo ha sido editado", "Confirmacion", JOptionPane.INFORMATION_MESSAGE);
            else JOptionPane.showMessageDialog(this, "Ha ocurrido un error en la edicion. \n Por favor, intente nuevamente.", "Error", JOptionPane.ERROR_MESSAGE);
         }
    }

    private void bloquearPorPermisos() {
         if (ventanaPrincipal.getPermisos().getPermisoPapel().indexOf(UtilUsuarios.VER)>-1){
            btnEditar.setVisible(false);
            btnEditar.setEnabled(false);
            btnGuardar.setVisible(false);
            btnGuardar.setEnabled(false);
            btnAgregarSeccion.setEnabled(false);
            btnAgregarSeccion.setVisible(false);
            btnEditarSeccion.setEnabled(false);
            btnEditarSeccion.setVisible(false);
            btnEliminarSeccion.setVisible(false);
            btnEliminarSeccion.setEnabled(false);
        }        
        if (ventanaPrincipal.getPermisos().getPermisoPapel().indexOf(UtilUsuarios.CREAR)>-1){
            btnEditar.setVisible(false);
            btnEditar.setEnabled(false);
            btnGuardar.setVisible(true);
            btnGuardar.setEnabled(true);
            btnAgregarSeccion.setEnabled(true);
            btnAgregarSeccion.setVisible(true);
            btnEditarSeccion.setEnabled(false);
            btnEditarSeccion.setVisible(false);
            btnEliminarSeccion.setVisible(true);
            btnEliminarSeccion.setEnabled(true);
        }                
        if (ventanaPrincipal.getPermisos().getPermisoPapel().indexOf(UtilUsuarios.EDITAR)>-1){
            btnEditar.setVisible(true);
            btnEditar.setEnabled(true);
            btnGuardar.setVisible(true);
            btnGuardar.setEnabled(true);
            btnAgregarSeccion.setEnabled(true);
            btnAgregarSeccion.setVisible(true);
            btnEditarSeccion.setEnabled(true);
            btnEditarSeccion.setVisible(true);
            btnEliminarSeccion.setVisible(true);
            btnEliminarSeccion.setEnabled(true);
        }
    }



}
